from django.contrib import auth
from django.contrib.auth.forms import UserCreationForm


def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            home = create_directory(name=user.username, owner=user)
            username = user.username
            raw_password = form.cleaned_data.get('password1')
            user = auth.authenticate(username=username, password=raw_password)
            auth.login(request, user)
            return HttpResponseRedirect(reverse('share:index'))
    else:
        form = UserCreationForm()
    context = {'form': form, 'title': 'Sign up'}
    return render(request, 'share/signup.html', context=context)


def login(request):
    next_url = request.GET.get('next', reverse('share:index'))
    if request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            # 先对比验证码，再校验用户名字和密码
            posted_captcha = form.cleaned_data['captcha']
            saved_captcha = get_session_data(request, 'captcha')
            if (saved_captcha is not None
                    and posted_captcha.lower() == saved_captcha):
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                user = auth.authenticate(username=username, password=password)
                if user is not None and user.is_active:
                    auth.login(request, user)
                    return HttpResponseRedirect(next_url)
            else:
                form.add_error('captcha','验证码不匹配')
    else:
        form = LoginForm()
    context = {'form': form, 'title': 'Login', 'login_page': True}
    return render(request, 'share/login.html', context=context)


def logout(request):
    auth.logout(request)
    return HttpResponseRedirect(reverse('share:index'))
